<template>
  <div class="student-stats">
    <!-- 头部信息区域 - 优化了背景颜色 -->
    <div class="header">
      <div class="title-container">
        <h1 class="main-title">学员信息统计</h1>
        <p class="sub-title">全面分析学员结构与分布情况</p>
      </div>
      <div class="actions">
        <el-button type="primary" icon="Refresh" @click="fetchData" round>刷新数据</el-button>
        <el-button icon="Download" @click="exportData" round>导出报表</el-button>
      </div>
    </div>

    <!-- 统计概览 -->
    <div class="summary-cards">
      <div class="summary-card total">
        <div class="card-content">
          <div class="card-icon">
            <el-icon><User /></el-icon>
          </div>
          <div class="card-info">
            <div class="card-value">{{ totalStudents }}</div>
            <div class="card-label">学员总数</div>
          </div>
        </div>
      </div>

      <div class="summary-card max-class">
        <div class="card-content">
          <div class="card-icon">
            <el-icon><School /></el-icon>
          </div>
          <div class="card-info">
            <div class="card-value">{{ maxClassCount }}</div>
            <div class="card-label">最多学员班级</div>
          </div>
        </div>
      </div>

      <div class="summary-card top-degree">
        <div class="card-content">
          <div class="card-icon">
            <el-icon><Reading /></el-icon>
          </div>
          <div class="card-info">
            <div class="card-value">{{ topDegree }}</div>
            <div class="card-label">主要学历分布</div>
          </div>
        </div>
      </div>

      <div class="summary-card ratio">
        <div class="card-content">
          <div class="card-icon">
            <el-icon><PieChart /></el-icon>
          </div>
          <div class="card-info">
            <div class="card-value">{{ degreeRatio }}%</div>
            <div class="card-label">本科及以上比例</div>
          </div>
        </div>
      </div>
    </div>

    <!-- 图表区域 -->
    <div class="charts-container">
      <div class="chart-card">
        <div class="chart-header">
          <h2 class="chart-title">班级人数分布</h2>
          <div class="chart-actions">
            <el-tag :type="classChartType === 'bar' ? 'primary' : 'success'" effect="dark">
              {{ classChartType === 'bar' ? '柱状图' : '饼图' }}
            </el-tag>
            <el-tooltip content="切换图表类型" placement="top">
              <el-button icon="Switch" circle plain @click="toggleClassChartType" />
            </el-tooltip>
          </div>
        </div>

        <div v-loading="loading" element-loading-background="rgba(255, 255, 255, 0.8)">
          <div v-if="classData.clazzList.length === 0 && !loading" class="empty-state">
            <el-empty description="暂无数据" />
          </div>
          <div v-else class="chart-container" ref="classChart"></div>
        </div>
      </div>

      <div class="chart-card">
        <div class="chart-header">
          <h2 class="chart-title">学员学历分布</h2>
          <div class="chart-actions">
            <el-tag :type="degreeChartType === 'pie' ? 'success' : 'primary'" effect="dark">
              {{ degreeChartType === 'pie' ? '饼图' : '柱状图' }}
            </el-tag>
            <el-tooltip content="切换图表类型" placement="top">
              <el-button icon="Switch" circle plain @click="toggleDegreeChartType" />
            </el-tooltip>
          </div>
        </div>

        <div v-loading="loading" element-loading-background="rgba(255, 255, 255, 0.8)">
          <div v-if="degreeData.length === 0 && !loading" class="empty-state">
            <el-empty description="暂无数据" />
          </div>
          <div v-else class="chart-container" ref="degreeChart"></div>
        </div>
      </div>
    </div>

    <!-- 底部信息 - 移除了数据来源 -->
    <div class="footer">
      <div class="update-info">
        <el-icon><Clock /></el-icon>
        <span>最后更新: {{ lastUpdateTime }}</span>
      </div>
    </div>
  </div>
</template>

<script setup>
import { ref, onMounted, computed, watch, nextTick, onUnmounted } from 'vue'
import * as echarts from 'echarts'
import { ElMessage } from 'element-plus'
import {
  User,
  PieChart,
  Refresh,
  Download,
  Switch,
  Clock,
  School,
  Reading,
} from '@element-plus/icons-vue'
import { queryStudentCountDataApi, queryStudentDegreeDataApi } from '@/api/report'

// 图表DOM引用
const classChart = ref(null)
const degreeChart = ref(null)

// 图表实例引用
const classChartInstance = ref(null)
const degreeChartInstance = ref(null)

// 数据状态
const classData = ref({
  clazzList: [],
  dataList: [],
})
const degreeData = ref([])
const loading = ref(false)
const classChartType = ref('bar') // 'bar' or 'pie'
const degreeChartType = ref('pie') // 'pie' or 'bar'

// 修复：使用响应式变量存储最后更新时间
const lastUpdateTimestamp = ref(new Date())

// 计算属性
const totalStudents = computed(() => {
  return classData.value.dataList.reduce((sum, num) => sum + num, 0)
})

const maxClassCount = computed(() => {
  if (classData.value.dataList.length === 0) return 0
  return Math.max(...classData.value.dataList)
})

const topDegree = computed(() => {
  if (degreeData.value.length === 0) return '无数据'

  const maxDegree = degreeData.value.reduce((max, item) => (item.value > max.value ? item : max), {
    name: '',
    value: 0,
  })

  return maxDegree.name
})

const degreeRatio = computed(() => {
  if (totalStudents.value === 0) return 0

  const highDegree = ['本科', '硕士', '博士']
  const highDegreeCount = degreeData.value
    .filter((item) => highDegree.includes(item.name))
    .reduce((sum, item) => sum + item.value, 0)

  return ((highDegreeCount / totalStudents.value) * 100).toFixed(1)
})

// 修复：基于响应式时间戳计算最后更新时间
const lastUpdateTime = computed(() => {
  return formatDateTime(lastUpdateTimestamp.value)
})

// 格式化日期时间
const formatDateTime = (date) => {
  return date.toLocaleString('zh-CN', {
    year: 'numeric',
    month: '2-digit',
    day: '2-digit',
    hour: '2-digit',
    minute: '2-digit',
    second: '2-digit',
  })
}

// 获取数据
const fetchData = async () => {
  try {
    loading.value = true
    // 获取班级数据
    const classResponse = await queryStudentCountDataApi()
    classData.value = classResponse.data

    // 获取学历数据
    const degreeResponse = await queryStudentDegreeDataApi()
    degreeData.value = degreeResponse.data

    // 更新最后更新时间戳
    lastUpdateTimestamp.value = new Date()

    // 初始化图表
    initClassChart()
    initDegreeChart()

    ElMessage.success('数据刷新成功')
  } catch (error) {
    console.error('获取数据失败:', error)
    ElMessage.error('数据加载失败，请稍后重试')
  } finally {
    loading.value = false
  }
}

// 导出数据
const exportData = () => {
  ElMessage.success('导出功能已触发')
}

// 切换班级图表类型
const toggleClassChartType = () => {
  classChartType.value = classChartType.value === 'bar' ? 'pie' : 'bar'
  initClassChart()
}

// 切换学历图表类型
const toggleDegreeChartType = () => {
  degreeChartType.value = degreeChartType.value === 'pie' ? 'bar' : 'pie'
  initDegreeChart()
}

// 初始化班级分布图表
const initClassChart = () => {
  if (!classChart.value || classData.value.clazzList.length === 0) return

  // 销毁旧实例
  if (classChartInstance.value) {
    classChartInstance.value.dispose()
  }

  // 创建新实例
  classChartInstance.value = echarts.init(classChart.value)

  let option

  if (classChartType.value === 'bar') {
    option = {
      tooltip: {
        trigger: 'axis',
        axisPointer: {
          type: 'shadow',
        },
        formatter: '{b}: {c}人',
      },
      grid: {
        left: '3%',
        right: '4%',
        bottom: '15%',
        containLabel: true,
      },
      xAxis: {
        type: 'category',
        data: classData.value.clazzList,
        axisLabel: {
          rotate: 30,
          interval: 0,
          fontSize: 12,
        },
      },
      yAxis: {
        type: 'value',
        name: '人数',
      },
      series: [
        {
          name: '学员数量',
          type: 'bar',
          barWidth: '60%',
          data: classData.value.dataList,
          itemStyle: {
            color: function (params) {
              const colorList = ['#5470c6', '#91cc75', '#fac858', '#ee6666', '#73c0de', '#3ba272']
              return colorList[params.dataIndex % colorList.length]
            },
          },
          label: {
            show: true,
            position: 'top',
            formatter: '{c}人',
          },
        },
      ],
    }
  } else {
    // 饼图模式
    const pieData = classData.value.clazzList.map((clazz, index) => ({
      name: clazz,
      value: classData.value.dataList[index],
    }))

    option = {
      tooltip: {
        trigger: 'item',
        formatter: '{a} <br/>{b}: {c}人 ({d}%)',
      },
      legend: {
        orient: 'vertical',
        right: 10,
        top: 'center',
        data: classData.value.clazzList,
      },
      series: [
        {
          name: '班级分布',
          type: 'pie',
          radius: ['40%', '70%'],
          avoidLabelOverlap: false,
          itemStyle: {
            borderRadius: 10,
            borderColor: '#fff',
            borderWidth: 2,
          },
          label: {
            show: true,
            formatter: '{b}: {c}人',
          },
          emphasis: {
            label: {
              show: true,
              fontSize: '14',
              fontWeight: 'bold',
            },
          },
          labelLine: {
            show: true,
          },
          data: pieData,
        },
      ],
    }
  }

  classChartInstance.value.setOption(option)
}

// 初始化学历分布图表
const initDegreeChart = () => {
  if (!degreeChart.value || degreeData.value.length === 0) return

  // 销毁旧实例
  if (degreeChartInstance.value) {
    degreeChartInstance.value.dispose()
  }

  // 创建新实例
  degreeChartInstance.value = echarts.init(degreeChart.value)

  let option

  if (degreeChartType.value === 'pie') {
    option = {
      tooltip: {
        trigger: 'item',
        formatter: '{a} <br/>{b}: {c}人 ({d}%)',
      },
      legend: {
        orient: 'horizontal',
        bottom: 10,
        data: degreeData.value.map((item) => item.name),
      },
      series: [
        {
          name: '学历分布',
          type: 'pie',
          radius: ['40%', '70%'],
          avoidLabelOverlap: false,
          itemStyle: {
            borderRadius: 10,
            borderColor: '#fff',
            borderWidth: 2,
          },
          label: {
            show: true,
            formatter: '{b}: {c}人\n({d}%)',
          },
          emphasis: {
            label: {
              show: true,
              fontSize: '18',
              fontWeight: 'bold',
            },
          },
          labelLine: {
            show: true,
          },
          data: degreeData.value,
        },
      ],
    }
  } else {
    // 柱状图模式
    const degrees = degreeData.value.map((item) => item.name)
    const values = degreeData.value.map((item) => item.value)

    option = {
      tooltip: {
        trigger: 'axis',
        axisPointer: {
          type: 'shadow',
        },
        formatter: '{b}: {c}人',
      },
      grid: {
        left: '3%',
        right: '4%',
        bottom: '3%',
        containLabel: true,
      },
      xAxis: {
        type: 'category',
        data: degrees,
        axisLabel: {
          fontSize: 14,
        },
      },
      yAxis: {
        type: 'value',
        name: '人数',
      },
      series: [
        {
          name: '学历分布',
          type: 'bar',
          barWidth: '40%',
          data: values,
          itemStyle: {
            color: function (params) {
              const colorMap = {
                博士: '#5470c6',
                硕士: '#91cc75',
                本科: '#fac858',
                大专: '#ee6666',
                高中: '#73c0de',
                初中: '#3ba272',
                其他: '#9a60b4',
              }
              return colorMap[degrees[params.dataIndex]] || '#ff9d6f'
            },
          },
          label: {
            show: true,
            position: 'top',
            formatter: '{c}人',
          },
        },
      ],
    }
  }

  degreeChartInstance.value.setOption(option)
}

// 响应窗口大小变化
const handleResize = () => {
  if (classChartInstance.value) {
    classChartInstance.value.resize()
  }
  if (degreeChartInstance.value) {
    degreeChartInstance.value.resize()
  }
}

// 组件挂载时获取数据
onMounted(() => {
  fetchData()
  window.addEventListener('resize', handleResize)
})

// 组件卸载时清理资源
onUnmounted(() => {
  window.removeEventListener('resize', handleResize)

  // 销毁图表实例
  if (classChartInstance.value) {
    classChartInstance.value.dispose()
  }
  if (degreeChartInstance.value) {
    degreeChartInstance.value.dispose()
  }
})

// 监听数据变化，重新渲染图表
watch(
  classData,
  () => {
    nextTick(() => {
      initClassChart()
    })
  },
  { deep: true },
)

watch(
  degreeData,
  () => {
    nextTick(() => {
      initDegreeChart()
    })
  },
  { deep: true },
)
</script>

<style scoped>
.student-stats {
  padding: 20px;
  max-width: 1400px;
  margin: 0 auto;
  display: flex;
  flex-direction: column;
  gap: 24px;
  background-color: #f5f7fa;
  min-height: 100vh;
}

/* 头部样式 - 优化了背景颜色 */
.header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  flex-wrap: wrap;
  gap: 20px;
  padding: 16px 24px;
  background: linear-gradient(135deg, #3a7bd5, #00d2ff); /* 更美观的蓝色渐变 */
  border-radius: 16px;
  color: white;
  box-shadow: 0 6px 18px rgba(0, 0, 0, 0.15);
}

.title-container {
  display: flex;
  flex-direction: column;
}

.main-title {
  font-size: 1.8rem;
  font-weight: 700;
  margin: 0;
  letter-spacing: 0.5px;
  text-shadow: 1px 1px 2px rgba(0, 0, 0, 0.2);
}

.sub-title {
  margin: 8px 0 0;
  font-size: 1rem;
  opacity: 0.9;
  text-shadow: 1px 1px 1px rgba(0, 0, 0, 0.2);
}

.actions {
  display: flex;
  gap: 12px;
}

/* 统计卡片样式 */
.summary-cards {
  display: grid;
  grid-template-columns: repeat(auto-fit, minmax(240px, 1fr));
  gap: 20px;
}

.summary-card {
  background: white;
  border-radius: 12px;
  padding: 20px;
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.08);
  transition: all 0.3s ease;
}

.summary-card:hover {
  transform: translateY(-5px);
  box-shadow: 0 8px 20px rgba(0, 0, 0, 0.15);
}

.total {
  border-top: 4px solid #3a7bd5; /* 与头部主色调一致 */
}

.max-class {
  border-top: 4px solid #36b5b0;
}

.top-degree {
  border-top: 4px solid #e6a23c;
}

.ratio {
  border-top: 4px solid #f56c6c;
}

.card-content {
  display: flex;
  align-items: center;
  gap: 20px;
}

.card-icon {
  display: flex;
  align-items: center;
  justify-content: center;
  width: 60px;
  height: 60px;
  border-radius: 50%;
  font-size: 28px;
  color: white;
}

.total .card-icon {
  background: linear-gradient(135deg, #3a7bd5, #00d2ff); /* 与头部一致 */
}

.max-class .card-icon {
  background: linear-gradient(135deg, #36b5b0, #1d6b5c);
}

.top-degree .card-icon {
  background: linear-gradient(135deg, #e6a23c, #d25f00);
}

.ratio .card-icon {
  background: linear-gradient(135deg, #f56c6c, #c41d7f);
}

.card-value {
  font-size: 2.2rem;
  font-weight: 700;
  line-height: 1;
  color: #333;
}

.card-label {
  font-size: 0.95rem;
  color: #666;
  margin-top: 8px;
}

/* 图表区域样式 */
.charts-container {
  display: grid;
  grid-template-columns: repeat(auto-fit, minmax(600px, 1fr));
  gap: 24px;
}

.chart-card {
  background: white;
  border-radius: 16px;
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.08);
  overflow: hidden;
  transition: all 0.3s ease;
}

.chart-card:hover {
  box-shadow: 0 8px 24px rgba(0, 0, 0, 0.12);
}

.chart-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 20px 24px 0;
}

.chart-title {
  font-size: 1.4rem;
  font-weight: 600;
  color: #2c3e50;
  margin: 0;
}

.chart-actions {
  display: flex;
  align-items: center;
  gap: 10px;
}

.chart-container {
  height: 420px;
  width: 100%;
  padding: 10px;
}

.empty-state {
  display: flex;
  align-items: center;
  justify-content: center;
  height: 400px;
  color: #999;
}

/* 底部样式 - 移除了数据来源 */
.footer {
  display: flex;
  justify-content: flex-end; /* 右对齐 */
  padding: 16px 24px;
  background: white;
  border-radius: 12px;
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.05);
  font-size: 0.9rem;
  color: #666;
}

.update-info {
  display: flex;
  align-items: center;
  gap: 8px;
}

/* 响应式调整 */
@media (max-width: 1200px) {
  .charts-container {
    grid-template-columns: 1fr;
  }
}

@media (max-width: 768px) {
  .header {
    flex-direction: column;
    align-items: flex-start;
    gap: 16px;
  }

  .summary-cards {
    grid-template-columns: 1fr 1fr;
  }

  .chart-container {
    height: 350px;
  }
}

@media (max-width: 576px) {
  .summary-cards {
    grid-template-columns: 1fr;
  }

  .footer {
    justify-content: center; /* 在小屏幕上居中 */
  }
}
</style>
